package game.windows;


import game.shared.Constants;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Buttons;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

public class Button extends WindowControl {
	protected TextureRegion  tButtonNomal;
	protected TextureRegion  tButtonPressed;
	protected boolean pressed;
	protected boolean oldLeftClick;
	protected boolean newLeftClick;
	protected int functionCode;
	
	public Button(){
	}
	
	public Button(Button bt){
		this.tButtonNomal = bt.tButtonNomal;
		this.tButtonPressed = bt.tButtonPressed;
		pressed = false;
		oldLeftClick = false;
		this.width = tButtonNomal.getRegionWidth();
		this.height =  tButtonNomal.getRegionHeight();
		this.functionCode = bt.functionCode;
		this.id = -1;
		this.idGroup = 0;
	}
	
	public Button(int functionCode, TextureRegion  tButtonNomal, TextureRegion  tButtonPressed)
	{
		this.tButtonNomal = tButtonNomal;
		this.tButtonPressed = tButtonPressed;
		pressed = false;
		oldLeftClick = false;
		this.width = tButtonNomal.getRegionWidth();
		this.height =  tButtonNomal.getRegionHeight();
		this.functionCode = functionCode;
		id = -1;
		this.idGroup = 0;
	}
	
	public Button(int idGroup, int functionCode, TextureRegion  tButtonNomal, TextureRegion  tButtonPressed)
	{
		this.tButtonNomal = tButtonNomal;
		this.tButtonPressed = tButtonPressed;
		pressed = false;
		oldLeftClick = false;
		this.width = tButtonNomal.getRegionWidth();
		this.height =  tButtonNomal.getRegionHeight();
		this.functionCode = functionCode;
		id = -1;
		this.idGroup = idGroup;
	}
	
	@Override
	public void update() {
		newLeftClick = Gdx.input.isButtonPressed(Buttons.LEFT);
		
		if(isOver())
		{
			if(newLeftClick == true && oldLeftClick == false)
			{
				pressed = true;
				Constants.set_RETURN_VALUE(1); 
				Constants.set_RETURN_CODE(functionCode);
			}			
		}
		
		if(newLeftClick == false && oldLeftClick == true)
		{
			pressed = false;
			Constants.set_RETURN_VALUE(pressed == true ? 1 : 0); 
			Constants.set_RETURN_CODE(Constants.FUNCTION_CODE_NONE);
		}
		oldLeftClick = newLeftClick;
	}
	
	public boolean isOver()
	{
		int x = Gdx.input.getX();
		int y = Constants.SCREEN_HEIGHT - Gdx.input.getY();
		
		if((this.x<x) && (x<this.x+this.width))
			if((this.y<y) && (y<this.y+this.height))
				return true;
		return false;
	}
	
	@Override
	public void render(SpriteBatch sb) {
		if(pressed)
		{
			if(tButtonPressed != null)
				sb.draw(tButtonPressed, x, y);
		}
		else
		{
			if(tButtonNomal != null)
				sb.draw(tButtonNomal, x, y);
		}
	}
}
